package com.gljx.web.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import com.gljx.web.Entity.Menu;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gljx.constant.Constant;
import com.gljx.util.CommonUtil;
import com.gljx.web.dao.SystemMapper;
import com.gljx.web.dao.UserMapper;
import com.gljx.web.Entity.Company;
import com.gljx.web.Entity.Power;
import com.gljx.web.Entity.User;
import com.gljx.web.service.SysService;

@Service
public class SysServiceImpl implements SysService{

	@Autowired
	private UserMapper userDao;

	@Autowired
	private SystemMapper sysDao;

	@Value("${student.clear.alert.day}")
	private String days;

	@Override
	public User selectByPrimaryKey(String userName) {
		
		return  userDao.selectByPrimaryKey(userName,Constant.Project_ID);
	}


	@Override
	public User selectUser(User user) {
		
		return userDao.selectUser(user);
	}
	
	@Override
	public List<User> selectEasCreatUser(){
		return sysDao.selectEasCreatUser();
	}


	@Override
	public String menuMemory(String v_menu_url,		//菜单地址
											String v_user_number,	//账户
											String v_PROJECTNUMBER) {//项目标识
		Map <String,Object > data = new HashMap<String, Object>();
		data.put("v_user_number",v_user_number );
		data.put("v_now_time", CommonUtil.nowTime());
		data.put("v_PROJECTNUMBER", v_PROJECTNUMBER);
		data.put("v_menu_url", v_menu_url);
		sysDao.menuMemory(data);
		return (String)data.get("v_result");
	}


	@Override
	public String InsertCompanyUser(String companyID, String nowTime, Integer userID) {
		Map <String,Object > data = new HashMap<String, Object>();
		data.put("v_userId", userID);
		data.put("v_companyID",companyID );
		data.put("v_now_time", nowTime);
		sysDao.companyMemory(data);
		return (String)data.get("v_result");
	}


	@Override
	public List<Company> selectCompanyByUser(Integer userId, Integer company_num) {

		return sysDao.selectCompanyByUser(userId, company_num);
	}


	/**
	 * 查询当前用户菜单
	 */
	/*@Override
	public List<Power> findTree(Integer userId, String PID) {

		Date start_time_Menu = new Date();

		List<Menu> menus = sysDao.testFindTree(userId,PID);

		Iterator<Menu> menusIT = menus.iterator();

		int leavelInit = 1;

		List<List<Menu>> memusList = new ArrayList<List<Menu>>();

		List<Menu> chindList = new ArrayList<Menu>();

		boolean flag = true;

		//1.将菜单根据 层级拆分成菜单组。
		while(flag) {
			Menu m = menusIT.next();
			if(m.getLeavel() != leavelInit)
			{
				leavelInit = m.getLeavel();
				memusList.add(new ArrayList<>(chindList));
				chindList.clear();
			}
			chindList.add(m);
			flag = menusIT.hasNext();
			if(!flag)
			{
				memusList.add(new ArrayList<>(chindList));
				chindList.clear();
			}
		}

		//2.将list组装。

		//倒数第二个数组编号

		for(int lastSize = memusList.size()-2; lastSize >= 0;lastSize--)
		{
			List<Menu> outMenus =  memusList.get(lastSize);//将同一层级的菜单组取出

			//下一层级的菜单
			Iterator<Menu> menuChid = null;

			//遍历本层级菜单
			for(int i = 0 ;i < outMenus.size();i++)
			{

				//从源获取下一层级菜单
				menuChid = memusList.get(lastSize+1).iterator();

				Menu inMenu = outMenus.get(i);//本层级菜单

				//菜单类型是父菜单类型才进行判断
				if( "sys".equals(inMenu.getMenuType()))
				{
					//System.out.println("集合大小"+memusList.get(lastSize+1).size());

					//循环判别参数
					boolean forFlag = true;

					//是否正在进行装载
					boolean nowAdd = false;

					while (forFlag){

						Menu menu = menuChid.next();//子菜单（下一层级）

						forFlag = menuChid.hasNext();//下一个对象是否存在

						//如果下层级菜单的 父ID == 层级菜单ID
						if((menu.getParentId()).equals(inMenu.getId()))
						{
							//正在装载
							if(!nowAdd){ nowAdd = true; }

							chindList.add(menu);

							menuChid.remove();//删除

							//当没有元素时将数据设置在 本层级的菜单中
							if(!forFlag)
							{
								inMenu.setChildren(new ArrayList<>(chindList));
							}
						}
						else if(nowAdd||!forFlag)//正在装载时 或者最后一个对象时 停止循环并装载
						{
							inMenu.setChildren(new ArrayList<>(chindList));
							forFlag = false;
						}

					}

					chindList.clear();
				}

			}

		}


		Date start_time_Power = new Date();

		List<Power> powers = sysDao.findTree(userId, PID);

		Iterator<Power> it = powers.iterator();
		int i=1;
		i = getSize(it,i);
		for(int j = 0 ;j<=i;j++){
			it = powers.iterator();
			removeNull(it);
		}

		Date end_time_Power = new Date();

		long menuTimes = start_time_Power.getTime() - start_time_Menu.getTime();

		long powerTimes = end_time_Power.getTime() - start_time_Power.getTime();

		System.out.println("新的菜单生成方法："+menuTimes+" 毫秒");
		System.out.println("老的菜单生成："+powerTimes+" 毫秒");
		*//*Date start_time3 = new Date();
		SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String s_start_time3 = df3.format(start_time3);
		System.out.println("递归结束·"+s_start_time3);*//*
		return powers;
	}*/

	@Override
	public List<Menu> findUserMenuTree(Integer userId, String PID) {
		List<Menu> menus = sysDao.testFindTree(userId,PID);

		Iterator<Menu> menusIT = menus.iterator();

		int leavelInit = 1;

		List<List<Menu>> memusList = new ArrayList<List<Menu>>();

		List<Menu> chindList = new ArrayList<Menu>();

		boolean flag = true;

		//1.将菜单根据 层级拆分成菜单组。
		while(flag) {
			Menu m = menusIT.next();
			if(m.getLeavel() != leavelInit)
			{
				leavelInit = m.getLeavel();
				memusList.add(new ArrayList<>(chindList));
				chindList.clear();
			}
			chindList.add(m);
			flag = menusIT.hasNext();
			if(!flag)
			{
				memusList.add(new ArrayList<>(chindList));
				chindList.clear();
			}
		}

		//2.将list组装。

		//倒数第二个数组编号

		for(int lastSize = memusList.size()-2; lastSize >= 0;lastSize--)
		{
			List<Menu> outMenus =  memusList.get(lastSize);//将同一层级的菜单组取出

			//下一层级的菜单
			Iterator<Menu> menuChid = null;

			//遍历本层级菜单
			for(int i = 0 ;i < outMenus.size();i++)
			{

				//从源获取下一层级菜单
				menuChid = memusList.get(lastSize+1).iterator();

				Menu inMenu = outMenus.get(i);//本层级菜单

				//菜单类型是父菜单类型才进行判断
				if( "sys".equals(inMenu.getMenuType()))
				{
					//System.out.println("集合大小"+memusList.get(lastSize+1).size());

					//循环判别参数
					boolean forFlag = menuChid.hasNext();//下一个对象是否存在

					//是否正在进行装载
					boolean nowAdd = false;

					while (forFlag){

						Menu menu = menuChid.next();//子菜单（下一层级）

						forFlag = menuChid.hasNext();//下一个对象是否存在

						//如果下层级菜单的 父ID == 层级菜单ID
						if((menu.getParentId()).equals(inMenu.getId()))
						{
							//正在装载
							if(!nowAdd){ nowAdd = true; }

							chindList.add(menu);

							menuChid.remove();//删除

							//当没有元素时将数据设置在 本层级的菜单中
							if(!forFlag)
							{
								inMenu.setChildren(new ArrayList<>(chindList));
							}
						}
						else if(nowAdd||!forFlag)//正在装载时 或者最后一个对象时 停止循环并装载
						{
							inMenu.setChildren(new ArrayList<>(chindList));
							forFlag = false;
						}

					}

					chindList.clear();
				}

			}

		}
		List<Menu> resultMenu = memusList.get(0);
		Iterator<Menu> it = resultMenu.iterator();
		int i=5;
		//i = getSize(it,i);
		for(int j = 0 ;j<=i;j++){
			it = resultMenu.iterator();
			removeNull(it);
		}

		return resultMenu;
	}

	/**
	 * 将菜单添加到结果集中。
	 * @Author:  LiXiang
	 * @Date: Created in 2018/3/2 9:41
	 */
	private void addMenu(Menu menu,List<List<Menu>> memusList){
		if(memusList.size() >0)
		{
			//添加
		    memusList.get(memusList.size()-1).add(menu);
		}
		else
		{
		   // memusList.
		}
	}

	/**
	 * 去空
	* @param it
	* @author LiXiang  @date 2017年11月14日 下午3:36:57
	 */
	public void removeNull(Iterator<Menu> it){
		while(it.hasNext()){
			Menu m = it.next();
			if(m.getChildren() != null && m.getChildren().size()>0){
				Iterator<Menu> it2 = m.getChildren().iterator();
				removeNull(it2);
			}else{
				if("sys".equals(m.getMenuType())){
					it.remove();
				}
			}
		}
	}
	/**
	 * 获取层级
	* @param it
	* @param i
	* @return
	* @author LiXiang  @date 2017年11月14日 下午3:37:05
	 */
	public int getSize(Iterator<Power> it,int i){
		boolean flag =true;
		while(it.hasNext()){
			Power p = it.next();
		    if(p.getChildren().size()>0 && flag){
		    	flag = false;
		    	Iterator<Power> it2 = p.getChildren().iterator();
		    	getSize(it2,++i);
		    }
		}
		return i;
	}

	public boolean getMessageFlag(){
		//获取当前账户session
		Session session = SecurityUtils.getSubject().getSession();

		Integer flag= sysDao.selectHasMessage((String) SecurityUtils.getSubject().getPrincipal(),
				(String) session.getAttribute(Constant.CompanyId_session),Constant.Project_ID);
		return flag > 0 ;
	}

}
